#pragma once
#include <iostream>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include<cstring>
#include"common.hpp"
class InetAddr // 网络地址与本地地址的转化
{
public:
    InetAddr(struct sockaddr_in &addr)
        : _addr(addr)
    {
        //网络转主机
        _port = ntohs(addr.sin_port);
        char ipbuffer[64];
        inet_ntop(AF_INET, &_addr.sin_addr, ipbuffer, sizeof(_addr));
        _ip = ipbuffer;
    }
    InetAddr(const std::string &ip,uint16_t port)
    :_ip(ip)
    ,_port(port)
    {
        //主机转网络
        memset(&_addr,0,sizeof(_addr));
        _addr.sin_family=AF_INET;
        _addr.sin_port=htons(_port);
        inet_pton(AF_INET,_ip.c_str(),&_addr.sin_addr);
    }
    InetAddr(uint16_t port)
    :_port(port)
    {
        //主机转网络-服务端
        memset(&_addr,0,sizeof(_addr));
        _addr.sin_family=AF_INET;
        _addr.sin_port=htons(_port);
        //inet_pton(AF_INET,_ip.c_str(),&_addr.sin_addr);
        _addr.sin_addr.s_addr=INADDR_ANY;
    }
    uint16_t Port() { return _port; }
    std::string Ip() { return _ip; }
    bool operator==(const InetAddr& q)
    {
        return _port==q._port&&_ip==q._ip;
    }
     std::string StringAddr()
    {
        return _ip + ":" + std::to_string(_port);
    }
    const struct sockaddr_in &NetAddr() { return _addr; }
     const struct sockaddr *NetAddrPtr()
    {
        return CONV(_addr);
    }
    socklen_t NetAddrLen()
    {
        return sizeof(_addr);
    }
    ~InetAddr()
    {
    }

private:
    struct sockaddr_in _addr;
    uint16_t _port;
    std::string _ip;
};